package com.zr.service.sys.impl;

import com.github.pagehelper.PageHelper;
import com.mysql.cj.util.StringUtils;
import com.zr.mapper.sys.UserMapper;
import com.zr.mapper.sys.UserRoleMapper;
import com.zr.service.sys.UserInterface;
import com.zr.util.Md5Util;
import com.zr.util.RedisUtils;
import com.zr.util.TokenUtil;
import com.zr.vo.sys.User;
import com.zr.vo.sys.UserRole;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class UserServerImpl implements UserInterface {
    @Resource
    private UserMapper userMapper;

    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private TokenUtil tokenUtil;

    @Resource
    private UserRoleMapper userRoleMapper;
    @Override
    public List<User> selectByUser(User usr) {
        //使用分页插件按照浏览器传过来的参数对查询结果进行分页显示
        PageHelper.startPage(usr.getPageNum(),usr.getPageSize());
        return userMapper.selectByUser(usr);
    }

    @Override
    public void insert(User usr) {
        //如果有密码插入，就将密码使用Md5加密
        if(usr.getPassword()!=null){
            String md5Password=new Md5Util().EncoderByMd5(usr.getPassword());
            usr.setPassword(md5Password);
        }
        userMapper.insertSelective(usr);
    }

    @Override
    public User login(User usr) {
        String md5Password=Md5Util.EncoderByMd5(usr.getPassword());
        usr.setPassword(md5Password);
        return userMapper.login(usr);
    }

    @Override
    public String getImgByUrl(@Nullable String imgUrl) {
        if(StringUtils.isNullOrEmpty(imgUrl)) return null;
        File file=new File(imgUrl);
        byte[] b=null;
        try(FileInputStream fis=new FileInputStream(file)){
            b=new byte[(int)file.length()];
            fis.read(b);
        }catch (IOException e){
            e.printStackTrace();
        }
        return Base64.getEncoder().encodeToString(b);
    }

    @Override
    public void change(@NotNull User usr) {
        //获取原对象的userId和status属性，封装到新的对象中
        User u = new User();
        u.setUserId(usr.getUserId());
        u.setStatus(usr.getStatus());
        u.setModifyTime(new Date());
        u.setModifyId(tokenUtil.getUserId());
        //只更新有数据的列
        userMapper.updateByPrimaryKeySelective(u);
    }

    @Transactional
    @Override
    public void add(@NotNull User usr) {
        //对密码进行加密处理
        usr.setPassword(Md5Util.EncoderByMd5(usr.getPassword()));
        usr.setStatus("1");
        usr.setCreateId(tokenUtil.getUserId());
        usr.setCreateTime(new Date());
        userMapper.insertSelective(usr);
        if(usr.getRoles() != null){
            for(Long roleId : usr.getRoles()){
                UserRole userRole = new UserRole();
                userRole.setRoleId(roleId);
                userRole.setUserId(usr.getUserId());
                userRoleMapper.insert(userRole);
            }
        }
    }

    @Transactional
    @Override
    public void edit(@NotNull User usr) {
        //如果密码不为空就重设密码
        if(!StringUtils.isNullOrEmpty(usr.getPassword())){
            usr.setPassword(Md5Util.EncoderByMd5(usr.getPassword()));
        }
        //删除该用户所有角色
        userRoleMapper.deleteByUserId(usr);
        //为该用户新建角色
        if(usr.getRoles()!=null){
            for(Long roleId:usr.getRoles()){
                UserRole userRole = new UserRole();
                userRole.setRoleId(roleId);
                userRole.setUserId(usr.getUserId());
                userRoleMapper.insert(userRole);
            }
        }
        usr.setModifyTime(new Date());
        usr.setModifyId(tokenUtil.getUserId());
        userMapper.updateByPrimaryKeySelective(usr);
    }

    @Override
    public void del(@NotNull String userId) {
        userMapper.deleteByPrimaryKey(userId);
        User usr=new User();
        usr.setUserId(userId);
        userRoleMapper.deleteByUserId(usr);
    }

    @Override
    public String uploadImg(@NotNull MultipartFile file) throws IOException {
        //生成文件路径
        String extensionName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String path = "/Users/zhaoxinyu/Desktop/PicUploadTest/" + UUID.randomUUID().toString() + extensionName;
        //生成该路径下的文件
        File imgFile = new File(path);
        //将file存入该路径
        file.transferTo(imgFile);
        User user = userMapper.selectByPrimaryKey(tokenUtil.getUserId());
        user.setImgUrl(path);
        userMapper.updateByPrimaryKeySelective(user);
        return getImgByUrl(path);
    }

    @Override
    public void logout() {
        redisUtils.remove(tokenUtil.getToken());
    }


}
